package com.group.config;


import com.alibaba.fastjson.JSONObject;
import com.group.aop.ExceptionLogin;
import com.group.common.jwt.ClaimsStorage;
import com.group.common.utils.JwtUtil;
import com.group.common.utils.StaticConfig;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

@Configuration
public class LoginGlobalFliter implements GlobalFilter, Order {

    @Autowired
    JwtUtil jwt;


    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @ExceptionLogin
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        HashMap<String,String> a = ClaimsStorage.a;
        String path = exchange.getRequest().getURI().getPath();
        System.out.println(path);
        //判断是否为登录需要的路径
        if (StaticConfig.PASS_PATH.contains(path)){
            return chain.filter(exchange);
        }

        try{
            String token = exchange.getRequest().getHeaders().get("token").get(0);
            Claims claims = jwt.parseJWT(token);
            //判断是否携带token访问网关。
            if (claims!=null){
                String id = claims.getId();
                String subject = claims.getSubject();
                a.put("id",id);
                System.out.println("id:"+id+",subject:"+subject);
                Object roles = claims.get("roles");
                if ("admin".equals(roles)){
                    return chain.filter(exchange);
                }

            }

        } catch(Exception e){ new NullPointerException();
        }


        ServerHttpResponse response = exchange.getResponse();
        JSONObject message = new JSONObject();
        message.put("status", 403);
        message.put("data", "鉴权失败，请重新登录");
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int value() {
        return 0;
    }
}
